package interview;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author distantstar
 * @version 1.0
 * @date 2021
 * @description interview
 * @since JDK1.8
 */
public class SpecialDepthNodeList {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    private static class ListNode {
        int val;
        ListNode next;
        ListNode (int x) { val = x; }
    }

    public static ListNode[] listOfDepth(TreeNode tree) {
        if (tree == null) {
            return new ListNode[0];
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(tree);
        List<ListNode> lists = new ArrayList<>();
        ListNode no = new ListNode(-1);

        while (!queue.isEmpty()) {
            ListNode node = no;
            int size = queue.size();
            TreeNode temp;

            for (int i = 0; i < size; i++) {
                temp = queue.poll();
                node.next = new ListNode(temp.val);
                node = node.next;

                if (temp.left != null) {
                    queue.offer(temp.left);
                }
                if (temp.right != null) {
                    queue.offer(temp.right);
                }
            }

            lists.add(no.next);
        }

        ListNode[] res = new ListNode[lists.size()];
        for (int i = 0; i < lists.size(); i++) {
            res[i] = lists.get(i);
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode tree = new TreeNode(1);
        tree.left = new TreeNode(2);
        tree.left.left = new TreeNode(4);
        tree.left.left.left = new TreeNode(8);
        tree.left.right = new TreeNode(5);
        tree.right = new TreeNode(3);
        tree.right.right = new TreeNode(7);

        ListNode[] nodes = listOfDepth(tree);
        for (ListNode node : nodes) {
            while (node != null) {
                System.out.print(node.val + " ");
                node = node.next;
            }
            System.out.println();
        }
    }
}
